﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using Microsoft.WindowsAzure.StorageClient;

namespace UploadBlobToAzure
{
    public partial class downloadBlobDirectly : Form
    {
        field_validator fv = new field_validator();
        public List<CloudBlob> blobListToBeDeleted = new List<CloudBlob>();
        string folderLocation=string.Empty;
        string folderName=string.Empty;
        string blobEndPoint=string.Empty;
        string accountKey=string.Empty;
        string folderToBeDownloaded=string.Empty;
        string fileToBeDownloaded=string.Empty;
        string blobUri = string.Empty;
        string fileName = string.Empty;
        string[] linesDestLog={string.Empty};
        string totalFilesTransfered = string.Empty;
        string filesTranferedSuccessfully = string.Empty;
        string filesFailed = string.Empty;
        public downloadBlobDirectly()
        {
            InitializeComponent();
            lblFolderLocation.Text = "There is no folder selected, please select a folder before proceeding";
        }

        public void setToBeDeletedList(List<CloudBlob> m_blobList)
        {
            blobListToBeDeleted.Clear();
            blobListToBeDeleted.AddRange(m_blobList);              
        }

        public void setBlobEndPoint(string m_blobEndPoint)
        {
            blobEndPoint = m_blobEndPoint;
        }

        public void setaccountKey(string m_accountKey)
        {
            accountKey = m_accountKey;
        }



        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (browseFolder.ShowDialog() == DialogResult.OK)
            {
                folderLocation = browseFolder.SelectedPath.Trim();
                folderName = Path.GetFileName(folderLocation);
            }
            else
            {
                folderName = string.Empty;
                folderLocation = string.Empty;
            }
            if (folderLocation != string.Empty)
            {
                lblFolderLocation.Text = "The Folder Selected is :" + folderLocation;
                
            }
            else
            {
                lblFolderLocation.Text = "There is no folder selected, please select a folder before proceeding";
            }
        }

        
        private void btnDownload_Click(object sender, EventArgs e)
        {

            foreach (CloudBlob blobItem in blobListToBeDeleted)
            {
                 MessageBox.Show(blobItem.Uri.ToString());
                 blobUri = blobItem.Uri.ToString();
                 fileToBeDownloaded = blobUri.Substring((blobUri.LastIndexOf("/")) + 1);
                 string extension = fileToBeDownloaded.Substring(fileToBeDownloaded.IndexOf(".") + 1);
 
                 if (fileToBeDownloaded.IndexOf(".") != -1)
                 {
                     folderToBeDownloaded = blobUri.Substring(0, blobUri.LastIndexOf("/"));
                 }
                 else
                 {
                     folderToBeDownloaded = blobUri;
                 }
                try
                {
                    //folderName = fileToBeDownloaded.Substring(0, fileToBeDownloaded.LastIndexOf("/"));
                    //fileName = fileToBeDownloaded.Substring(fileToBeDownloaded.LastIndexOf("/") + 1);
                        if(fv.testIfFieldEmpty(folderLocation))
                        {
                            MessageBox.Show("Please select a Local Location To Download The Blob!!");
                            this.DialogResult = DialogResult.None;
                        }
                        else if(extension.Equals("vhd"))
                        {
                            MessageBox.Show("Cannot download the vhd of the VM from Azure!!,Please chose files of some other extension");
                            this.DialogResult = DialogResult.None;
                        }
                        else if (fileToBeDownloaded.IndexOf(".") != -1)
                        {
                            //folderName = fileToBeDownloaded.Substring(0, fileToBeDownloaded.LastIndexOf("/"));
                            //fileName = fileToBeDownloaded.Substring(fileToBeDownloaded.LastIndexOf("/") + 1);
                            Process cmd = new Process();
                            ProcessStartInfo azcopyProcessStartInfo = new ProcessStartInfo();
                            azcopyProcessStartInfo.FileName = "CMD.exe";
                            string cmdToBeExecuted = " azcopy.exe" + "  \"" + folderToBeDownloaded + "\"  " + "  \"" + folderLocation + "\"  " + fileToBeDownloaded + "  /sourceKey:" + accountKey + "  /S   /v  /Y  >dest.log";
                            azcopyProcessStartInfo.Arguments = "/c " + cmdToBeExecuted;
                            azcopyProcessStartInfo.UseShellExecute = false;
                            azcopyProcessStartInfo.CreateNoWindow = true;
                            azcopyProcessStartInfo.RedirectStandardError = true;
                            cmd.StartInfo = azcopyProcessStartInfo;
                            cmd.Start();
                            if (!cmd.StandardError.ReadToEnd().Equals(string.Empty))
                            {
                                MessageBox.Show("The following Error occurred :" + cmd.StandardError.ReadToEnd());
                            }
                            cmd.WaitForExit();

                            /*validate the activity*/

                            int output = validateCompletedRequest();
                            if (output == 0)
                            {
                                this.DialogResult = DialogResult.None;
                            }
                            else if (output == 1)
                            {
                                this.Close();
                            }
                            else if (output == 2)
                            {
                                this.DialogResult = DialogResult.Cancel;
                                this.Close();
                            }          
                        }
                        else
                        {
                            Process cmd = new Process();
                            ProcessStartInfo azcopyProcessStartInfo = new ProcessStartInfo();
                            azcopyProcessStartInfo.FileName = "CMD.exe";
                            string cmdToBeExecuted = " azcopy.exe" + "  \"" + folderToBeDownloaded + "\"  " + "  \"" + folderLocation + "\"  " + " /sourceKey:" + accountKey + "  /S   /v  /Y  >dest.log";
                            azcopyProcessStartInfo.Arguments = "/c " + cmdToBeExecuted;
                            azcopyProcessStartInfo.UseShellExecute = false;
                            azcopyProcessStartInfo.CreateNoWindow = true;
                            azcopyProcessStartInfo.RedirectStandardError = true;
                            cmd.StartInfo = azcopyProcessStartInfo;
                            cmd.Start();
                            //if (!cmd.StandardError.ReadToEnd().Equals(string.Empty))
                            //{
                            //    MessageBox.Show("The following Error occurred :" + cmd.StandardError.ReadToEnd());
                            //}
                            cmd.WaitForExit();

                            /*validate the activity*/

                            int output = validateCompletedRequest();
                            if (output == 0)
                            {
                                this.DialogResult = DialogResult.None;
                            }
                            else if (output == 1)
                            {
                                this.Close();
                            }
                            else if (output == 2)
                            {
                                this.DialogResult = DialogResult.Cancel;
                                this.Close();
                            }          
                        }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    this.DialogResult = DialogResult.None;
                }
            }

                  
        }


        private int validateCompletedRequest()
        {
            if (!File.Exists("dest.log"))
            {
                MessageBox.Show("The status of the Last operation cannot be determined as the Log file failed to generate in the application directory");
                //this.DialogResult = DialogResult.None;
                return 0;
            }
            else
            {
                linesDestLog = File.ReadAllLines("dest.log");
                foreach (var line in linesDestLog)
                {
                    if (line.Contains("Total files transferred"))
                    {
                        totalFilesTransfered = ((line.Substring(line.IndexOf(":") + 1)).Trim());
                    }
                    else if (line.Contains("Transfer successfully"))
                    {
                        filesTranferedSuccessfully = ((line.Substring(line.IndexOf(":") + 1)).Trim());
                    }
                    else if (line.Contains("Transfer failed"))
                    {
                        filesFailed = ((line.Substring(line.IndexOf(":") + 1)).Trim());
                    }
                }

                if (totalFilesTransfered == null || filesTranferedSuccessfully == null)
                {
                    MessageBox.Show("The status of the Last operation cannot be determined as the Log file failed to generate in the application directory");
                    //this.DialogResult = DialogResult.None;
                    return 0;
                }

                if (totalFilesTransfered.Equals(filesTranferedSuccessfully))
                {
                    DialogResult result = MessageBox.Show("All Files Transfered Successfully!!, You want to transfer another set of files?", "Question", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        //this.DialogResult = DialogResult.None;
                        return 0;
                    }
                    else
                    {
                        //this.Close();
                        return 1;
                    }
                }
                else if (filesTranferedSuccessfully == "0")
                {
                    MessageBox.Show("The Operation Failed, Kindly refer to the Dest.log in the Application directory for more details");

                    //this.DialogResult = DialogResult.Cancel;
                    //this.Close();
                    return 2;
                }
                else
                {
                    MessageBox.Show("Sone of the Files did not upload successfully, Please refer to the dest.log in the Application directory for details");
                    //this.Close();
                    return 1;
                }
            }
        }

        private void downloadBlob_Load(object sender, EventArgs e)
        {

        }
     }
}
